package com.example.ws.config;

import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;

public class DemoWebsocketHandler extends TextWebSocketHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(DemoWebsocketHandler.class);


    private static final Map<String,WebSocketSession > users = Maps.newConcurrentMap();




    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String username = getUserName(session);
        // 获取提交过来的消息详情
        LOGGER.debug("收到用户 " + username + "的消息:" + message.toString());
    }


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String username = getUserName(session);
        users.put(username, session);
    }


    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        String username = getUserName(session);
        users.remove(username);
    }

    public void send(String msg,String account){
        WebSocketSession  o = users.get(account);
        try {
            if(o!= null &&o.isOpen()){
                o.sendMessage(new TextMessage(msg));
            }else{
                LOGGER.debug("用户不在线，无法发送消息...");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    private String getUserName(WebSocketSession session){
        return (String) session.getAttributes().get("WEBSOCKET_USERNAME");
    }



}
